package logic

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"week/model/mysql"
	"week/user-srv/internal/svc"
	"week/user-srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type RealAuthLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRealAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RealAuthLogic {
	return &RealAuthLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RealAuthLogic) RealAuth(in *user.RealAuthRequest) (*user.RealAuthResponse, error) {
	// todo: add your logic here and delete this line
	r := mysql.RealAuth{
		UserId:   int(in.UserId),
		IdCard:   in.IdCard,
		RealName: in.RealName,
	}
	err := r.FindUserId()
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		logx.Error("查询实名信息失败", err)
		return nil, errors.New("查询实名信息失败")
	}
	if r.ID != 0 {
		return &user.RealAuthResponse{Success: true}, nil
	}
	err = r.FindIdCard()
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		logx.Error("查询实名信息失败", err)
		return nil, errors.New("查询实名信息失败")
	}
	if r.ID != 0 {
		return &user.RealAuthResponse{Success: true}, nil
	}
	return &user.RealAuthResponse{Success: false}, nil
}
